package memberrewards.dao;

import hackathon1212.EMF;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import memberrewards.entities.CatalogItem;

public class CatalogServiceDAO {

	private CatalogServiceDAO() {
	}

	public static ArrayList<CatalogItem> getEligibleCatalogList(String tier) {
		ArrayList<CatalogItem> eligibleCatalogList = null;
		List<CatalogItem> allCatalogList=getAllEligibleCatalogList();
		System.out.println("allCatalogList "+allCatalogList.size());
		if(allCatalogList!=null){
			eligibleCatalogList=new ArrayList<CatalogItem>();
			for (CatalogItem catalogItem : allCatalogList) {
				if(catalogItem.getTierList().contains(tier)){
					eligibleCatalogList.add(catalogItem);
				}
			}
		}
		return eligibleCatalogList;
	}
	
	public static CatalogItem getCatalogItem(String itemid) {
		CatalogItem  catalogItem = null;
		EntityManager entityManager=EMF.get().createEntityManager();
		try{
			catalogItem=entityManager.find(CatalogItem.class, itemid);
		}
		catch (IllegalArgumentException iaExc){
			return null;
		}
		finally{
			entityManager.close();
		}
		return catalogItem;
	}
	
	@SuppressWarnings("unchecked")
	private static List<CatalogItem> getAllEligibleCatalogList() {
		List<CatalogItem> allCatalogList = null;
		EntityManager entityManager=EMF.get().createEntityManager();
		try{
			Query query=entityManager.createQuery("SELECT ci FROM CatalogItem AS ci ");
			allCatalogList=query.getResultList();
		}
		finally{
			entityManager.close();
		}
		return allCatalogList;
	}

	public static ArrayList<CatalogItem> getSearchResult(String tier, String searchKey ) {
		ArrayList<CatalogItem> eligibleCatalogForTier = getEligibleCatalogList(tier);
		System.out.println("eligibleCatalogForTier "+eligibleCatalogForTier.size());
		ArrayList<CatalogItem> searchResults = new ArrayList<CatalogItem>();
		if(eligibleCatalogForTier!=null){
			for (CatalogItem catalogItem : eligibleCatalogForTier){
				if (catalogItem.getDescription().toLowerCase().contains(searchKey.toLowerCase())){
					searchResults.add(catalogItem);
				}
			}
		}
		System.out.println("searchResults "+searchResults.size());
		return searchResults;
	}
}